package org.qufenqi.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zhenzi.sms.ZhenziSmsClient;
import net.sf.jsqlparser.statement.execute.Execute;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.qufenqi.api.common.CommonResponse;
import org.qufenqi.api.common.HttpUtils;
import org.qufenqi.api.entity.Account;
import org.qufenqi.api.entity.Quota;
import org.qufenqi.api.entity.School;
import org.qufenqi.api.mapper.AccountMapper;
import org.qufenqi.api.mapper.QuotaMapper;
import org.qufenqi.api.mapper.SchoolMapper;
import org.qufenqi.api.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private QuotaMapper quotaMapper;

    //注册
    @Override
    public CommonResponse<Account> register(Account account) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        QueryWrapper<Account> queryWrapper1 = new QueryWrapper<>();
        queryWrapper.select("phone").like("phone",account.getPhone());
        queryWrapper1.eq("username",account.getUsername());
        if(accountMapper.selectList(queryWrapper).size()!=0||accountMapper.selectList(queryWrapper1).size()!=0){
            return CommonResponse.responseForErrorMessage("用户已存在");
        }

        accountMapper.insert(account);
        System.out.println(account);

        Quota quota = new Quota();
        quota.setQuota(5000);
        quota.setUserId(account.getUserId()+"");
        quotaMapper.insert(quota);


        return CommonResponse.responseForSuccess(account);
    }

    //用户名登录
    @Override
    public CommonResponse<Account> login(String name, String psw) {
        //redis字符串序列化器
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);

        //查询缓存
        String jsonList = JSON.toJSONString(redisTemplate.opsForValue().get(name + "Info"));
        Account userinfo = JSON.parseObject(jsonList,Account.class);

        if(userinfo == null){
            System.out.println("从数据库中获取数据");
            //缓存为空，查询一遍数据库
            QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("*").eq("username", name);
            userinfo = accountMapper.selectOne(queryWrapper);
            if(userinfo==null){
                return CommonResponse.responseForErrorMessage("账号不存在!");
            }
            //把获得数据放入redis
            redisTemplate.opsForValue().set(name + "Info",userinfo,3L, TimeUnit.DAYS);
        }
        else {
            System.out.println("直接从缓存中获取数据");
        }



        if (psw.equals(userinfo.getPassword())) {
            return CommonResponse.responseForSuccess(userinfo);
        }
        return CommonResponse.responseForErrorMessage("密码错误");
    }

    //手机验证码
    @Override
    public CommonResponse<String> getMsg(String number)throws Exception{
        ZhenziSmsClient client = new ZhenziSmsClient("https://sms_developer.zhenzikj.com","109513","cb9450a2-74db-4748-9031-0fa7828dc2b3");
        Map<String,Object> params = new HashMap<String, Object>();
        String random = (int) ((Math.random() * 9 + 1) * 100000) + "";
        params.put("number",number);
        params.put("templateId",5998);
        String[] templateParams = new String[2];
        templateParams[0] = random;
        templateParams[1] = "5分钟";
        params.put("templateParams",templateParams);
        String result = client.send(params);

        String yue = client.balance();
        System.out.println(random + "\n" + result + "\n" + "余额："  + yue);

        JSONObject json = JSONObject.parseObject(result);
        if(json.getIntValue("code")!=0){//发送短信失败
            return CommonResponse.responseForErrorMessage("短信发送失败");
        }

        return CommonResponse.responseForSuccessMessage(random);
    }

    //身份证信息验证
    @Override
    public CommonResponse<Object> checkID(String name,String ID){
        String host = "https://idenauthen.market.alicloudapi.com";
        String path = "/idenAuthentication";
        String method = "POST";
        String appcode = "1abd63c7b09f4a888d5664c8a56dd844";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("idNo", ID);
        bodys.put("name", name);


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            String info = EntityUtils.toString(response.getEntity());
//            System.out.println(EntityUtils.toString(response.getEntity()));
            JSONObject jsonObject = JSON.parseObject(info);
            return CommonResponse.responseForSuccess(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonResponse.responseForErrorMessage("出现未知错误");
    }



    //插入用户身份证号
    public CommonResponse<Account> insertUserID(String username,String idnumber){

        //redis字符串序列化器
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);

        UpdateWrapper<Account> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("username",username).set("idnumber",idnumber);
        accountMapper.update(null,updateWrapper);

        try {
            redisTemplate.delete(username + "Info");
        }
        catch (Exception ex){
            System.out.println("无缓存，不需要删除");
        }


        return CommonResponse.responseForSuccess();
    }


    //改密码
    @Override
    public CommonResponse<String> changePSW(String username,String psw){

        //redis字符串序列化器
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);

        UpdateWrapper<Account> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("username",username).set("password",psw);
        accountMapper.update(null,updateWrapper);


        try {
            redisTemplate.delete(username+"Info");
        }
        catch (NullPointerException ex){
            System.out.println("无缓存，不需要删除");
        }


        return CommonResponse.responseForSuccess();
    }

    //验证学生证号
    @Override
    public CommonResponse<String> checkStudentId(String school,String studentName,String studentId){

        QueryWrapper<School> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("*").eq("school",school)
                .eq("studentname",studentName)
                .eq("studentid",studentId);

        if(schoolMapper.selectList(queryWrapper).size()!=0){
            return CommonResponse.responseForSuccess();
        }
        else {
            return CommonResponse.responseForErrorMessage("不存在该学生");
        }
    }

    //插入学生证号
    @Override
    public CommonResponse<String> insertStudentId(String username,String studentId){
        //redis字符串序列化器
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);

        UpdateWrapper<Account> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("username",username).set("studentid",studentId);
        accountMapper.update(null,updateWrapper);

        String Rediskey = username + "Info";
        System.out.println(Rediskey);
        try {
            redisTemplate.delete(Rediskey);
        }
        catch (Exception ex){
            System.out.println("无缓存，不需要删除");
        }


        return CommonResponse.responseForSuccess();
    }


    //更新信息
    public CommonResponse<Account> getUserInfo(String username){
        //redis字符串序列化器
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);

        //查询缓存
        String jsonList = JSON.toJSONString(redisTemplate.opsForValue().get(username + "Info"));
        Account userinfo = JSON.parseObject(jsonList,Account.class);

        if(userinfo == null){
            System.out.println("从数据库中获取数据");
            //缓存为空，查询一遍数据库
            QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("*").eq("username", username);
            System.out.println("名字" + username + "   !!!!!!!!!!!!!!!!!!!!!!!");
            userinfo = accountMapper.selectOne(queryWrapper);
            //把获得数据放入redis
            redisTemplate.opsForValue().set(username + "Info",userinfo,3L, TimeUnit.DAYS);
        }
        else {
            System.out.println("直接从缓存中获取数据");
        }


        return CommonResponse.responseForSuccess(userinfo);
    }

    //加钱
    @Override
    public CommonResponse<Account> addMoney(String username,double money){
        //redis字符串序列化器
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);

        //查询缓存
        String jsonList = JSON.toJSONString(redisTemplate.opsForValue().get(username + "Info"));
        Account userinfo = JSON.parseObject(jsonList,Account.class);

        if(userinfo == null){
            System.out.println("从数据库中获取数据");
            //缓存为空，查询一遍数据库
            QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("*").eq("username", username);
            userinfo = accountMapper.selectOne(queryWrapper);
            //把获得数据放入redis
            redisTemplate.opsForValue().set(username + "Info",userinfo,3L, TimeUnit.DAYS);
        }
        else {
            System.out.println("直接从缓存中获取数据");
        }


        UpdateWrapper<Account> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("username",username).set("usermoney",userinfo.getUsermoney()+money);
        accountMapper.update(null,updateWrapper);

        try {
            redisTemplate.delete(username + "Info");
        }
        catch (Exception ex){
            System.out.println("无缓存，不需要删除");
        }

        return CommonResponse.responseForSuccess();
    }
}
